package com.indexingsystem.boss.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;



public class TablesUtils 
{
    private static ApplicationContext context = null;
    private static JdbcTemplate jdbcTemplate = null;
    static{
        context = new ClassPathXmlApplicationContext("applicationContext.xml");   
        jdbcTemplate = (JdbcTemplate)context.getBean("jdbcTemplate"); 
    }
    
    /** 
     * 根据表名称创建一张表 
     * @param tableName 
     */  
    public static int createTable(String tableName,String context){ 
        
        StringBuffer sb = new StringBuffer("");  
        sb.append("CREATE TABLE `" + tableName + "` (");  
        sb.append(" `id` int(11) NOT NULL AUTO_INCREMENT,");  
//        Map<String,String> map = ObjectUtil.getProperty(obj);  
//        Set<String> set = map.keySet();  
//        for(String key : set){  
//            sb.append("`" + key + "` varchar(255) DEFAULT '',");  
//        }         
//        sb.append(" `tableName` varchar(255) DEFAULT '',");  
        sb.append(" PRIMARY KEY (`id`)");  
        sb.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");  
        try {  
            jdbcTemplate.update(sb.toString());  
            return 1;  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return 0;  
    }      
    

    /** 
     * 根据表名称创建一张表  
     * @param tableName 
     */  
    public static int executSql(String context) throws Exception{ 
    	int update = 0;
        update = jdbcTemplate.update(context);  
        if(update != -1){
            update = 1;
        }
        return update;  
    }     
    
    /**
     * 根据表名删除一张表
     * @param tableName
     * @return
     */
    public static int dropTable(String tableName) throws Exception{
    	int update = 0;
    	StringBuffer sb= new StringBuffer();
		sb.append("DROP TABLE IF EXISTS  `").append(tableName).append("`;");
        update = jdbcTemplate.update(sb.toString());  
        if(update != -1){
            update = 1;
        }
    	 return update;
    }
}